<?php
/**
 * @copyright © 2022 by 技术先锋 All rights reserved
 * @created   by PhpStorm.
 * @author    starsphp
 * @date      2023/3/23
 * @time      16:57
 */

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use utils\server\http\AdapterHttpServer;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;

AdapterHttpServer::init();

$http_worker                = new Worker('http://0.0.0.0:8787');
$http_worker->count         = cpu_count() * 4;
$http_worker->name          = 'AdapterHttpServer';

$http_worker->onWorkerStart = static function () {
    require_once __DIR__.'/utils/workerman/thinkHttpRun.php';
};

$http_worker->onMessage = static function (TcpConnection $connection,Request|array $request) {
    $connection->send(\run($request));
    // isAccessStaticFile($connection, $request);
    // dump($request['REQUEST_URI']);
    // $a = \run($request);
    // // dump($a);
    // $connection->send($a);
};

function isAccessStaticFile(TcpConnection $connection,Request|array $request)
{
    // $publicFile = __DIR__ . DIRECTORY_SEPARATOR . 'public' . $request['server']['REQUEST_URI'] ?? '';
    // dump($publicFile);
    // if (is_file($publicFile)) {
    //     accessStaticFile($connection, $request, $publicFile);
    //     return;
    // }
    $connection->send(\run($request));
}

function accessStaticFile(TcpConnection $connection,Request|array $request, $file)
{
    // $file = '/your/path/of/file';
    // 检查if-modified-since头判断文件是否修改过
    if (!empty($if_modified_since = $request['HTTP_' . 'IF_MODIFIED_SINCE'] ?? '')) {
        $modified_time = date('D, d M Y H:i:s',  filemtime($file)) . ' ' . \date_default_timezone_get();
        // 文件未修改则返回304
        if ($modified_time === $if_modified_since) {
            $connection->send(new Response(304));
            return;
        }
    }
    // 文件修改过或者没有if-modified-since头则发送文件
    $response = (new Response())->withFile($file);
    // \response()
    $response = \think\Response::create($file, 'file');
    dump($response);
    $connection->send($response);
}

Worker::runAll();
